package de.tudarmstadt.ukp.muip.fibqdojo.io;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.common.base.Optional;

/**
 * Abstract class which provides methods for reading data from a XML file.
 * 
 * @author Tobias Horsmann
 */
public abstract class Reader implements IO_Constants {
    
    protected NodeList getTopHierarchyData(File gold, String elementName) throws ParserConfigurationException,
            SAXException, IOException {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(gold);
        return doc.getElementsByTagName(elementName);
    }

    protected boolean isNodeNameEqualTo(Element element, String name) {
        return element.getNodeName().equals(name);
    }

    protected boolean isElementNode(Node item) {
        return item.getNodeType() == Node.ELEMENT_NODE;
    }

    protected Optional<String> getStringValueOfElement(Element element, String elementName) {
        Optional<String> stringValue = Optional.absent();
        if (isNodeNameEqualTo(element, elementName)) {
            Node firstChild = element.getFirstChild();
            if (firstChild != null) {
                String nodeValue = firstChild.getNodeValue();
                stringValue = Optional.of(nodeValue);
            }

        }
        return stringValue;
    }

}
